<?php
/**
 * @filename QuestionCommand.php 
 * @encoding UTF-8 
 * @author KangShuAn
 * @datetime 2014-11-25 10:00:51
 * @version 1.0
 * @Description 银行附件压缩包处理
 */
set_time_limit(0);
ini_set('memory_limit', -1);
class BankCommand extends CConsoleCommand
{
    const SEPARATE_MARK = '-';//字段分隔符
    private $path = '';//解压目录
    private $unzip_file = '';//解压后的文件
    private $nba_id = 0;//附件表索引
    
    private $file = '';//文件
    public function run($args){
	//得到未处理的问卷
        $zip = new NetworkBankZip();
        $criteria = new CDbCriteria();
        $criteria->addColumnCondition(array('is_dispose' => QuestionBase::QUESTION_ATTACHMENT));
	$list = $zip->findAll($criteria);
		
	if ($list) {
            foreach ($list as $key => $val) {
                $this->nba_id = $val['nba_id'];
                $this->file = dirname(Yii::app()->BasePath) .'/assets/bank_zip/'.$val['bank_id'].'_'.$val['nba_num'].'.zip';
                if (file_exists($this->file)) {
                    //先把状态改了，改成正处理
                    NetworkBankZip::model()->updateByPk($this->nba_id, array('update_time' => date('Y-m-d H:i:s'),'is_dispose' => QuestionBase::QUESTION_ATTACHMENT_UPLOADED));
                    $this->unzip($val['bank_id'],$val['nba_num']);
                    $this->Up($val);
                } else {
                    NetworkBankZip::model()->updateByPk($this->nba_id, array('update_time' => date('Y-m-d H:i:s'),'is_dispose' => QuestionBase::QUESTION_ATTACHMENT_EXECUTED,'remark' => '文件不存在'));
                }
            }
        }

    }

    /**
     * 上传附件
     * 扫描解压的文件，将附件一个个传到云平台
     * zip包名称为银行ID，一个银行一个zip包，里面是多个网点的
     * 101-2.png
     * 网点编号-说明
     */
    public function Up($zip_info){
        $bank_id = $zip_info['bank_id'];
        
        $arr = pathinfo($this->file);
	//问卷编号，压缩文件名称
        $identifier = explode('_',$arr['filename']);
        
        $bank = new NetworkBank();
        $bank_info = $bank->findByPk($bank_id);
	if (!$bank_info) {
            //没有此问卷，要更新附件状态，下次不再处理
            NetworkBankZip::model()->updateByPk($this->nba_id, array('update_time' => date('Y-m-d H:i:s'),'remark' => '没有此问卷','is_dispose' => QuestionBase::QUESTION_ATTACHMENT_EXECUTED));
            return false;
        }
        
        $fileobj = new File();
        //压缩文件目录
        $file = scandir($this->unzip_file);
        //错误信息
        $error = array();
	if ($file !== false) {
            foreach ($file as $val) {
                if ($val =='.' || $val=='..') continue; 
                $absolue_file = $this->unzip_file.DIRECTORY_SEPARATOR.$val;
                if (!is_dir($absolue_file)) {
                    $pathinfo = pathinfo($val);
                    $filename = $pathinfo['filename'];
                    echo $absolue_file."\r\n";
                    //continue;
                    //每个附件的名称
                    $attachment = explode(self::SEPARATE_MARK, $filename);
                    //网点编号
                    $network_num = $attachment[0];
                    //根据网点编号查找id
                    $network = new NetWork();
                    $network_info = $network->getByNetworkNum($network_num, $bank_id);
                    if (!$network_info) {
                        $error[] = $network_num.'网点编号不存在';
                        continue;
                    }
                    $network_id = (int)$network_info['network_id'];
                    echo '网点ID'.$network_id."\r\n";
                    
                    $file_dir = $this->unzip_file.DIRECTORY_SEPARATOR.$val;
                    echo $file_dir . " 开始上传~~\r\n";
                    //上传,下载时用中文名

                    $url = $fileobj->uploadByFile($val, $file_dir,'zhengda-benchmark', $val);
                    echo "返回url：".$url."\r\n";
					
                    //上传成功
                    if ($url) {
                        //保存附件
                        $network_attach = new NetworkAttach();
                        $network_attach->network_id = $network_id;
                        $network_attach->zip_name = $val;
                        $network_attach->url = $url;
                        $network_attach->create_time = time();
                        $network_attach->nba_id = $this->nba_id;

                        $attachSave = $network_attach->save();
                        if ($attachSave) {
                            echo "network_attach id ". $network_id ."，附件表写入成功！\r\n";
                        }
                    }
                } else {
                    $error[] = '存在二级目录';
                }
            }
            if (empty($error)) {
                $error[] = '解压上传成功';
            }
            NetworkBankZip::model()->updateByPk($this->nba_id, array('update_time' => date('Y-m-d H:i:s'),'is_dispose' => QuestionBase::QUESTION_ATTACHMENT_EXECUTED,'remark' => join(',', $error)));
            echo "question_base 附件状态更新成功\r\n";
        }
        echo "zip done\r\n";
        exit;
    }
    /**
     * 
     * @param type $file
     * 解压同级目录
     */
    private function unzip($bank_id, $nba_num){
        $this->unzip_file = substr($this->file, 0, -4);
        $command = escapeshellcmd("unzip -o {$this->file} -d /data/www/mystery/assets/bank_zip/{$bank_id}_{$nba_num}/");
        $result = exec($command,$output, $return);
        
        
        /*$zip = new ZipArchive();
        $res = $zip->open($this->file);
        $this->unzip_file = substr($this->file, 0, -4);
	if ($res === true) {
            $zip->extractTo($this->unzip_file);
            $zip->close();
        }*/
    } 
	
 
}